package com.iscc.maoke.dao.impl;

import com.iscc.maoke.dao.UserDAO;
import com.iscc.maoke.domain.User;
import com.iscc.maoke.util.DataSourceUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAOImpl implements UserDAO {
    @Override
    public int addUser(User user) {
        String sql = "INSERT INTO tab_user(account,PASSWORD,phone,uname) VALUES(?,?,?,?)";
        int result = -1;
        Connection conn = null;
        PreparedStatement psmt = null;
        try {
            //获取Connection对象
            conn = DataSourceUtil.getConnection();
            //获取预处理对象 PreparedStatement
            psmt = conn.prepareStatement(sql);
            //如果SQL中有占位符，给占位符赋值，没有过。
            psmt.setString(1, user.getAccount());
            psmt.setString(2, user.getPassword());
            psmt.setString(3, user.getPhone());
            psmt.setString(4, user.getAccount());
            //执行SQL: 查询- executeQuery, 增删改- executeUpdate() : int 影响行数;
            result = psmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DataSourceUtil.releaseResource(psmt, conn);
        }
        return result;
    }

    @Override
    public User login(String account) {
        User user = null;
        String sql = "SELECT * FROM tab_user WHERE account = ?";
        Connection conn = null;
        PreparedStatement psmt = null;
        ResultSet rs = null;
        try {
            conn = DataSourceUtil.getConnection();
            psmt = conn.prepareStatement(sql);
            psmt.setString(1, account);

            rs = psmt.executeQuery();
            if (rs.next()) {
                user = new User();
                user.setUno(rs.getInt(1));
                user.setAccount(rs.getString(2));
                user.setPassword(rs.getString(3));
                user.setPhone(rs.getString(4));
                user.setUimg(rs.getString(5));
                user.setStates(rs.getInt(6));
                user.setIntegral(rs.getInt(7));
                user.setBirth(rs.getString(8));
                user.setUname(rs.getString(9));
                user.setTemp1(rs.getString(10));
                user.setRoleid(rs.getInt(11));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DataSourceUtil.releaseResource(rs, psmt, conn);
        }

        return user;
    }
}
